<template>
  <div style="height: 400px">
    <el-button type="primary" :icon="Plus" size="small" @click="onClickAdd">添加</el-button>
    <el-button type="danger" :icon="Delete" size="small" @click="onClickDelete" :disabled="tableData.length === 0">删除</el-button>
    <el-table-v2 class="draggable" ref="dragTable" size="small" :columns="columns" :data="tableData" :width="700" :height="400" />
    <addCheck :visible="addCheckVisiable" @closeDialog="closeAddCheckDialog" @getSelectData="getSelectData"></addCheck>
  </div>
</template>

<script lang="tsx" setup>
import { ref, watch } from 'vue'
import { ElInput, ElCheckbox } from 'element-plus'
import {
  Delete,
  Plus,
} from '@element-plus/icons-vue'
import { default as Sortable, SortableEvent } from "sortablejs";
import type { FunctionalComponent } from 'vue'
import type { Column, InputInstance } from 'element-plus'
import addCheck from './addCheck.vue';
const props = defineProps({
  data: { type: Array, default: () => [] },
})


const addCheckVisiable = ref(false);
const selectData = ref([]);
const tableData = ref<any[]>([]);
const typeArr = [
   '选择项',
   '数字项',
   '文本项',
   '拍照项',
]

const onClickAdd = () => {
  addCheckVisiable.value = true;
}

const onClickDelete = () => {
  console.log(tableData.value, 'tableData')
  if (!tableData.value.some((item: any) => item.checked === true)) {
    return ElMessage.error('请选择要删除的项')
  }
  // 判断tableData中是否有checked的 或者 checked为true
  tableData.value = JSON.parse(JSON.stringify(tableData.value.filter((item: any, index: number) =>  !(item.checked || false) )))
  console.log('删除后：', tableData.value)
}

const getSelectData = (data: any) => {
  selectData.value = data;
  tableData.value = [...tableData.value, ...data];
  console.log(tableData.value, 'tableData')
  addCheckVisiable.value = false;
  rowDrag()
  console.log(selectData.value, 'selectData')
}

const closeAddCheckDialog = () => {
  addCheckVisiable.value = false;
}

type SelectionCellProps = {
  value: string
  intermediate?: boolean
  onChange: (value: string) => void
  forwardRef: (el: InputInstance) => void
}

const InputCell: FunctionalComponent<SelectionCellProps> = ({
  value,
  onChange,
  forwardRef,
}) => {
  return (
    <ElInput ref={forwardRef as any} onInput={onChange} modelValue={value} />
  )
}
const rowDrag = () => {
  const tbody = document.querySelector(
    ".el-table-v2__body")?.firstChild?.firstChild
  console.log(tbody, 'tbody')
  if (!tbody) return;
  Sortable.create(tbody as HTMLElement, {
    // 可被拖拽的子元素
    draggable: ".el-table-v2__row",
    handle: ".drag-handler",
    animation: 150,  // ms, number 单位：ms，定义排序动画的时间
    scroll: true, // or HTMLElement
    onStart: function (/**Event*/evt: any) {
      console.log(evt, 'ev123')
    },

    onEnd(event: SortableEvent) {
      console.log(event, 'event')
      if (event.oldIndex !== undefined && event.newIndex !== undefined) {
        const currRow = tableData.value.splice(event.oldIndex, 1)[0];
        tableData.value.splice(event.newIndex, 0, currRow);
      }
    }
  })
};


const columns = [
  {
    title: '序号',
    align: 'center',
    width: 80,
    key: 'index',
      cellRenderer: ({ rowData, column,  rowIndex}) => {
        console.log(rowIndex, 'rowIndex----')
    return (
      <span class="drag-handler" style="cursor: move;">{rowIndex +1}</span>
    )
  },
  },
  {
    key: 'selection',
  width: 50,
  cellRenderer: ({ rowData }: any) => {
    const onChange = (value: CheckboxValueType) => (rowData.checked = value)
    return <SelectionCell value={rowData.checked} onChange={onChange} />
  },

  headerCellRenderer: () => {
    const _data = unref(tableData.value)
    const onChange = (value: CheckboxValueType) =>
      (tableData.value = _data.map((row) => {
        row.checked = value
        return row
      }))
    const allSelected = _data.every((row) => row.checked)
    const containsChecked = _data.some((row) => row.checked)

    return (
      <SelectionCell
        value={allSelected}
        intermediate={containsChecked && !allSelected}
        onChange={onChange}
      />
    )
  },
  },
  {
    title: '检查项目名称',
    dataKey: 'itemsName',
    width: 300,
    key: 'itemsName',
    align: 'center',
  },
  {
    title: '抽检概率（%）',
    dataKey: 'chance',
    width: 200,
    key: 'chance',
    align: 'center',
    cellRenderer: ({ rowData, column }: any) => {
      console.log(rowData, column)
      const onChange = (value: string) => {
        rowData[column.dataKey!] = value
      }
      const onEnterEditMode = () => {
        rowData.editing = true
      }

      const onExitEditMode = () => (rowData.editing = false)
      const input = ref()
      const setRef = (el: { focus: () => void; }) => {
        input.value = el
        if (el) {
          el.focus?.()
        }
      }

      return rowData.editing ? (
        <InputCell
          forwardRef={setRef}
          value={rowData[column.dataKey!]}
          onChange={onChange}
          onBlur={onExitEditMode}
          onKeydownEnter={onExitEditMode}
        />
      ) : (
        <div class="table-v2-inline-editing-trigger" style="width: 80px;height: 30px;" onClick={onEnterEditMode}>
          {rowData[column.dataKey!]}
        </div>
      )
    },
  },
  {
    title: '类型',
    dataKey: 'itemsType',
    width: 150,
    key: 'itemsType',
    align: 'center',
    cellRenderer: ({ rowData }: any) => {
    return  <span>{typeArr[rowData.itemsType]}</span>
    }
  },
  {
    title: '必填',
    dataKey: 'isRequired',
    width: 150,
    key: 'isRequired',
    align: 'center',
    cellRenderer: ({ rowData }: any) => {
    return  <span>{rowData.isRequired === '0' ? '否' : '是'}</span>
    }
  },
  {
    title: '评分',
    dataKey: 'isScore',
    width: 150,
    key: 'isScore',
    align: 'center',
    cellRenderer: ({ rowData }: any) => {
    return  <span>{rowData.isScore === '0' ? '否' : '是'}</span>
    }
  },
]

// columns.unshift({
//   ...columns[0],
//   title: '拖拽',
//   cellRenderer: ({ rowData, column }) => {

//     return (
//       <svg-icon class="drag-handler" icon-class="drag" />
//     )
//   },
// })

type SelectionCellProps1 = {
  value: boolean
  intermediate?: boolean
  onChange: (value: CheckboxValueType) => void
}

const SelectionCell: FunctionalComponent<SelectionCellProps1> = ({
  value,
  intermediate = false,
  onChange,
}) => {
  return (
    <ElCheckbox
      onChange={onChange}
      modelValue={value}
      indeterminate={intermediate}
    />
  )
}

watch(
  () => props.data,
   (val) => {
    console.log(tableData.value, '------')
     tableData.value = val;
  },
  { deep: true, immediate: true },
);

defineExpose({
  tableData,
})
</script>

<style>
.table-v2-inline-editing-trigger {
  border: 1px transparent dotted;
  padding: 4px;
}

.el-table-v2__body {
  height: 500px;
}

.table-v2-inline-editing-trigger:hover {
  border-color: var(--el-color-primary);
}

::v-deep(.el-table-v2__header-wrapper) {
  height: 500px;
}
</style>
